from django.shortcuts import render
from django.http import HttpResponse
from common.models import User
from django.shortcuts import redirect
from django.core.urlresolvers import reverse

# 前台首页
def index(request):
    return render(request, "web/index.html")

def dologin(request):

    try:
        #根据账号获取登录者信息
        users = User.objects.get(username=request.POST['username'])
        #判断当前用户是否是后台管理员用户
        if users.status == 1:
            # 验证密码
            import hashlib
            m = hashlib.md5() 
            m.update(bytes(request.POST['password'],encoding="utf-8"))
            #print("pass:",users.password_hash)
            #print("pass2:",m.hexdigest())
            if users.password_hash == m.hexdigest():
                # 此处登录成功，将当前登录信息放入到session中，并跳转页面
                request.session['vipuser'] = users.toDict()
                return redirect(reverse('web_index'))
            else:
                context = {'info':'登录密码错误！'}
        else:
            context = {'info':'此用户为非法用户！'}

    except Exception as err:
        print(err)
        context = {'info':'登录账号错误！'}
    return render(request,"web/login.html",context)


def logout(request):
	'''会员退出'''
    # 清除登录的session信息
	del request.session['vipuser']
	# 跳转登录页面（url地址改变）
	return redirect(reverse('web_login'))

def login(request):
    return render(request, "web/login.html")
